<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="单据编号" prop="enquiryCode">
        <el-input
          v-model="queryParams.enquiryCode"
          placeholder="请输入询价单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据名称" prop="enquiryName">
        <el-input
          v-model="queryParams.enquiryName"
          placeholder="请输入询价单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据日期" prop="enquiryDate">
        <el-date-picker clearable
                        v-model="queryParams.enquiryDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择单据日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="询价截止时间" prop="enquiryDeadline">
        <el-date-picker clearable
                        v-model="queryParams.enquiryDeadline"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择询价截止时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="采购人" prop="buyer">
        <el-input
          v-model="queryParams.buyer"
          placeholder="请输入采购姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="草稿" value="0"/>
          <el-option label="询价中" value="1"/>
          <el-option label="定标中" value="2"/>
          <el-option label="待审批" value="3"/>
          <el-option label="已审批" value="4"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['cg:enquiry:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="enquiryList" @selection-change="handleSelectionChange">
      <el-table-column label="单据编号" align="center" prop="enquiryCode">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleInfo(scope.row)"
          >{{ scope.row.enquiryCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="单据名称" align="center" prop="enquiryName"/>
      <el-table-column label="单据日期" align="center" prop="enquiryDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.enquiryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === '0'">草稿</span>
          <span v-if="scope.row.status === '1'">询价中</span>
          <span v-if="scope.row.status === '2'">定标中</span>
          <span v-if="scope.row.status === '3'">待审批</span>
          <span v-if="scope.row.status === '4'">已审批</span>
        </template>
      </el-table-column>
      <el-table-column label="询价截止时间" align="center" prop="enquiryDeadline" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.enquiryDeadline, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="询价范围" align="center" prop="enquiryRange">
        <template slot-scope="scope">
          <span v-if="scope.row.enquiryRange === '0'">全部</span>
          <span v-if="scope.row.enquiryRange === '1'">指定供应商</span>
        </template>
      </el-table-column>
      <el-table-column label="采购人" align="center" prop="buyer"/>
      <el-table-column label="电话" align="center" prop="buyerPhone"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-coordinate"
            @click="handleConfirm(scope.row)"
            v-hasPermi="['cg:enquiry:confirm']"
            v-if="scope.row.status === '0'"
          >确认
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['cg:enquiry:edit']"
            v-if="scope.row.status === '0'"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['cg:enquiry:remove']"
            v-if="scope.row.status === '0'"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-add"
            @click="handleQuotation(scope.row)"
            v-hasPermi="['cg:enquiry:quotation']"
            v-if="scope.row.status === '1'"
          >报价
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-c-scale-to-original"
            @click="handleContrast(scope.row)"
            v-if="scope.row.status === '2'"
          >比价
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购管理-采购询价单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="95%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="询价单编号" prop="enquiryCode">
              <el-input v-model="form.enquiryCode" placeholder="请输入询价单编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="询价单名称" prop="enquiryName">
              <el-input v-model="form.enquiryName" placeholder="请输入询价单名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据日期" prop="enquiryDate">
              <el-date-picker clearable
                              v-model="form.enquiryDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择单据日期"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="询价截止时间" prop="enquiryDeadline">
              <el-date-picker clearable
                              v-model="form.enquiryDeadline"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择询价截止时间"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购员" prop="buyer">
              <el-input v-model="form.buyer" placeholder="请选择采购员" readonly>
                <el-button slot="append" @click="handleSelectUser" icon="el-icon-search"></el-button>
              </el-input>
              <UserSelect ref="userSelect" @onSelected="onUserSelected"></UserSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购员电话" prop="buyerPhone">
              <el-input v-model="form.buyerPhone" placeholder="请输入采购员电话"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="收货地址" prop="receivingAddress">
              <el-input v-model="form.receivingAddress" placeholder="请输入收货地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需求截止日期" prop="materialDeadline">
              <el-date-picker clearable
                              v-model="form.materialDeadline"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择需求截止日期"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="询价范围" prop="enquiryRange">
          <el-radio v-model="form.enquiryRange" label="0">全部</el-radio>
          <el-radio v-model="form.enquiryRange" label="1">指定供应商</el-radio>
          <el-button
            size="mini"
            type="primary"
            @click="handleSelectVendor()"
            v-if="form.enquiryRange==='1'"
          >选择
          </el-button>
        </el-form-item>
        <el-table border :data="cgPurchaseEnquiryRangeList" v-if="form.enquiryRange==='1'">
          <el-table-column label="供应商编号" align="center" prop="vendorCode"/>
          <el-table-column label="供应商名称" align="center" prop="vendorName"/>
          <el-table-column label="供应商等级" align="center" prop="vendorLevel">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.mes_vendor_level" :value="scope.row.vendorLevel"/>
            </template>
          </el-table-column>
          <el-table-column label="供应商状态" align="center" prop="vendorStatus"/>
          <el-table-column label="是否黑名单" align="center" prop="isBlacklist">
            <template slot-scope="scope">
              <span>{{ scope.row.isBlacklist === 'Y' ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleDeleteVendor(scope.row)"
                v-hasPermi="['cg:enquiry:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="margin-bottom: 20px;margin-right: 20px;">
          <el-col :span="1.5">
            <div style="font-size: 20px; margin-top: 5px">询价明细</div>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="handleAddLine" style="margin-left: 20px;">选择物料</el-button>
          </el-col>
          <el-col :span="2">
            <el-upload
              action="#"
              ref="upload"
              class="upload-demo"
              accept=".xlsx,.xls"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleUpload">
              <template >
                <el-button type="primary">导入</el-button>
              </template>
            </el-upload>

          </el-col>
        </el-row>
        <el-table border ref="lineTable" :data="cgPurchaseEnquiryLineList">
          <el-table-column label="物料编号" align="center" prop="itemCode"/>
          <el-table-column label="物料名称" align="center" prop="itemName"/>
          <el-table-column label="规格型号" align="center" prop="specification"/>
          <el-table-column label="单位" align="center" prop="unitOfMeasure"/>
          <el-table-column label="需求数量" align="center" prop="quantity">
            <div class="item" slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" controls-position="right" :min="1"
                               size="mini" style="width:90%"/>
            </div>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleDeleteLine(scope.row)"
                v-hasPermi="['cg:enquiry:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <VendorSelect ref="vendorSelect" @onSelected="onVendorSelected"/>
      <ItemSelect ref="itemSelect" @onSelected="onItemSelected"></ItemSelect>
    </el-dialog>
    <EnquiryInfoView ref="enquiryInfoView"></EnquiryInfoView>
  </div>
</template>

<script>
import {listEnquiry, getEnquiry, delEnquiry, addEnquiry, updateEnquiry,character,confirmEnquiry} from "@/api/mes/cg/enquiry";
import VendorSelect from "@/components/vendorSelect/multi.vue";
import UserSelect from "@/components/userSelect/single.vue";
import ItemSelect from "./itemSelect.vue";
import {getUserProfile} from "@/api/system/user";
import {genCode} from "@/api/system/autocode/rule"
import * as xlsx from "xlsx";
import {addEnquiryScheduling} from "@/api/monitor/job";
import EnquiryInfoView from "@/views/mes/cg/enquiry/infoView.vue";
export default {
  name: "Enquiry",
  dicts: ['mes_vendor_level'],
  components: {UserSelect, VendorSelect,ItemSelect,EnquiryInfoView},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购管理-采购询价单表格数据
      enquiryList: [],
      //询价范围数据
      cgPurchaseEnquiryRangeList: [],
      //询价明细数据
      cgPurchaseEnquiryLineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        enquiryCode: null, enquiryName: null, enquiryDate: null, enquiryDeadline: null, buyer: null, status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        enquiryCode: [
          {required: true, message: "询价单编号不能为空", trigger: "blur"}
        ],
        enquiryName: [
          {required: true, message: "询价单名称不能为空", trigger: "blur"}
        ],
        enquiryDate: [
          {required: true, message: "单据日期不能为空", trigger: "blur"}
        ],
        enquiryDeadline: [
          {required: true, message: "询价截止时间不能为空", trigger: "change"}
        ],
        buyer: [
          {required: true, message: "采购员不能为空", trigger: "blur"}
        ],
        materialDeadline: [
          {required: true, message: "需求截止日期不能为空", trigger: "change"}
        ],
        enquiryRange: [
          {required: true, message: "询价范围不能为空", trigger: "change"}
        ]
      },
      user: {},
    };
  },
  watch: {
    '$route'(to,from){
      if(from.name==='contrast'){
        this.getList();
      }
    }
  },
  created() {
    this.getList();
    this.getUser();
  },
  methods: {
    /** 查询采购管理-采购询价单列表 */
    getList() {
      this.loading = true;
      listEnquiry(this.queryParams).then(response => {
        this.enquiryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        enquiryCode: null,
        enquiryName: null,
        enquiryDate: new Date().toISOString().split('T')[0],
        enquiryDeadline: this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
        buyerId: this.user.userId,
        buyer: this.user.nickName,
        buyerPhone: this.user.phonenumber,
        receivingAddress: null,
        materialDeadline: new Date().toISOString().split('T')[0],
        enquiryRange: null,
        status: "0"
      };
      this.cgPurchaseEnquiryRangeList = [];
      this.cgPurchaseEnquiryLineList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.handleAutoGenChange();
      this.title = "添加采购管理-采购询价单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEnquiry(id).then(response => {
        this.form = response.data;
        this.cgPurchaseEnquiryRangeList = response.data.cgPurchaseEnquiryRangeList;
        this.cgPurchaseEnquiryLineList = response.data.cgPurchaseEnquiryLineList;
        this.open = true;
        this.title = "修改采购管理-采购询价单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.enquiryRange==='0'){
            this.form.cgPurchaseEnquiryRangeList = [];
          }else{
            if(this.cgPurchaseEnquiryRangeList.length<=0){
              this.$modal.msgError("请选择询价范围");
              return;
            }
            this.form.cgPurchaseEnquiryRangeList = this.cgPurchaseEnquiryRangeList;
          }
          if(this.cgPurchaseEnquiryLineList.length<=0){
            this.$modal.msgError("请添加询价明细");
            return;
          }
          for(var i=0;i<this.cgPurchaseEnquiryLineList.length;i++){
            const line = this.cgPurchaseEnquiryLineList[i];
            if(line.quantity<=0){
              this.$modal.msgError("询价明细需求数量必须大于0");
              return;
            }
          }
          this.form.cgPurchaseEnquiryLineList = this.cgPurchaseEnquiryLineList;
          if (this.form.id != null) {
            updateEnquiry(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEnquiry(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除询价单编号为"' + row.enquiryCode + '"的数据项？').then(function () {
        return delEnquiry(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleSelectVendor() {
      this.$refs.vendorSelect.showFlag = true;
      this.$refs.vendorSelect.selectedRows1 = this.cgPurchaseEnquiryRangeList;
      this.$refs.vendorSelect.resetQuery();
    },
    onVendorSelected(obj) {
      const result = this.cgPurchaseEnquiryRangeList.filter(item => obj.includes(item))
      const filteredArrayObj = obj.filter(objItem =>
        !result.some(rangeItem => rangeItem['vendorId'] === objItem['vendorId'])
      )
      this.cgPurchaseEnquiryRangeList = [...result, ...filteredArrayObj];
    },
    handleDeleteVendor(row){
      this.cgPurchaseEnquiryRangeList.splice(this.cgPurchaseEnquiryRangeList.indexOf(row), 1);
    },
    // 获取登录用户
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    handleSelectUser() {
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.buyer = obj.nickName;
        this.form.buyerId = obj.id;
        this.form.buyerPhone = obj.phonenumber;
      }
    },
    handleAddLine(){
    this.$refs.itemSelect.showFlag=true;
    this.$refs.itemSelect.getList();
    },
    handleDeleteLine(row){
      this.cgPurchaseEnquiryLineList.splice(this.cgPurchaseEnquiryLineList.indexOf(row), 1);
    },
    handleUpload(event){
      const file = event.raw;
      const reader=new FileReader();
      reader.onload=(e)=>{
        const data= new Uint8Array(e.target.result);
        const workbook= xlsx.read(data,{type:'array'});
        const worksheet=workbook.Sheets[workbook.SheetNames[0]];
        const jsonData=xlsx.utils.sheet_to_json(worksheet,{header:1});
        //表头数据
        let headers=jsonData[0];
        let array=[];
        jsonData.splice(1).forEach(row=>{
          const rowData=row.reduce((accumulator,item,index)=> {
            let key=headers[index];
            let v=character[key];
            if(v){
              let column=v.column;
              let type=v.type;
              if(type==='number' && item){
                accumulator[column]=Number(item);
              }else{
                accumulator[column]=item;
              }
            }
            return accumulator;

          },{})
          array.push(rowData);
        })
        this.onItemSelected(array);
      }
      reader.readAsArrayBuffer(file);
    },
    onItemSelected(obj){
      const result=Object.values(obj.reduce((acc, item) => {
        if(acc[item.itemCode]){
          acc[item.itemCode].quantity += item.quantity;
        }else{
          acc[item.itemCode] = {...item};
        }
        return acc;
      }, {}));
      this.cgPurchaseEnquiryLineList=result;
    },
    //自动生成编码
    handleAutoGenChange() {
      genCode('CG_ENQUIRY_CODE').then(response => {
        this.form.enquiryCode = response;
      });
    },
    handleConfirm(row){
      let that=this;
      that.$modal.confirm('是否确认确认询价单编号为"' + row.enquiryCode + '"的询价单？').then(function () {
        //判断截止时间是否在当前时间之后
        if(new Date(row.enquiryDeadline)<new Date()){
          that.$modal.msgError("截止时间不能早于当前时间");
          return;
        }
         confirmEnquiry(row.id)
           .then(() => {
           addEnquiryScheduling(row.id);
         }).then(() => {
           that.getList();
           that.$modal.msgSuccess("确认成功");
         }).catch(() => {
           console.log(12222222222)
         });
      })
    },
    handleQuotation(row){
      this.$router.push({name: 'quotation', params: row});
    },
    handleContrast(row){
      this.$router.push({name: 'contrast', params: row});
    },
    handleInfo(row){
      this.$refs.enquiryInfoView.init(row.id);
    }
    /** 导出按钮操作 */
    /*handleExport() {
      this.download('cg/enquiry/export', {
        ...this.queryParams
      }, `enquiry_${new Date().getTime()}.xlsx`)
    }*/
  }
};
</script>
